//
//  PopUpButton.m
//  AmountBody
//
//  Created by Qiu Jishuai on 2018/1/5.
//  Copyright © 2018年 RCMTM. All rights reserved.
//
#import "UIView+Extension.h"
#import "PopUpButton.h"


static const CGFloat kRightInset = 26.0f;

@implementation PopUpButton

- (void)setTitle:(NSString *)title {
    _title = title;
    [self setTitle:title forState:UIControlStateNormal];
    [self sizeToFit];
    if (self.width < 33) {
        self.width = 33;
    }
    self.width += 10;
}

- (void)showFromRect:(CGRect)rect inView:(UIView *)view {
    
    [view addSubview:self];
    [view bringSubviewToFront:self];
    
    self.x = CGRectGetMaxX(rect) - self.width;
    self.y = CGRectGetMinY(rect) - self.height;
    CGRect oldFrame = self.frame;
    //从箭头处开始缩放
    self.layer.anchorPoint = CGPointMake((self.width - kRightInset) / self.width, 1);
    self.frame = oldFrame;
    self.transform = CGAffineTransformMakeScale(0.001, 0.001);
    self.alpha = 0;

    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.alpha = 1;
        self.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [self dismiss];
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.25 delay:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.alpha = 0;
        self.transform = CGAffineTransformMakeScale(0.001, 0.001);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.titleEdgeInsets = UIEdgeInsetsMake(-3, 0, 3, 0);
    UIImage *image = [UIImage imageNamed:@"custom_embroidery_pop"];
    image = [image stretchImageWithInsetsTop:0 left:7 bottom:0 right:kRightInset];
    [self setBackgroundImage:image forState:UIControlStateNormal];
}

-(void)setImage:(UIImage *)image
{
    [self setBackgroundImage:image forState:UIControlStateNormal];
}

@end
